package cn.lr.basic.util;

import cn.lr.basic.jwt.JwtUtils;
import cn.lr.basic.jwt.Payload;
import cn.lr.basic.jwt.RsaUtils;
import cn.lr.basic.jwt.UserInfo;
import cn.lr.user.domain.Logininfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 登录上下文
 *  1.当前登录的信息  可能是Employee  也可能是user
 *  2.当前登录人的权限信息  以后玩
 *
 */
public class LoginContext {

    public static final String jwtRsaPublic = "hrm_auth_rsa.pub";//公钥的文件名字

    /**
     * 获取当前登录人
     * @param request
     * @return
     */
    public static Logininfo getLogininfo(HttpServletRequest request){
        //1.判断有没有携带token
        String token = request.getHeader("U-TOKEN");//JWT串
        //2.根据token 解密token得到登录人相关的所有信息
        try {
            PublicKey publicKey = RsaUtils
                    .getPublicKey((FileCopyUtils
                            .copyToByteArray(LoginContext.class.getClassLoader().getResourceAsStream(jwtRsaPublic))));
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            return userInfo.getUser();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
